#
# 飞书消息发送脚本
# cmd: python3 helper4FsErrNotify.py --NotifyType=test --FilePath=/Users/guodong/workspace1/guang-app/build/app/outputs/flutter-apk/app-ci-release.apk.qrcode.png
# desc: 上传文件到pgy，然后下载pgy二维码到apk/ipa同目录下， 生成.qrcode.png & .uploadRsp.json
# cmd2: python3 helper4FsErrNotify.py --NotifyType=test /
#   --BuildDesc="some-tips"
#   --BuildDesc=/Users/guodong/workspace1/guang-app/jenkins/../thisBuildDesc.md
#   --JenkinsBuildDescFile=/Users/guodong/workspace1/guang-app/jenkins/jenkinsBuildDesc.tmp
#   --AndPath=/Users/guodong/workspace1/guang-app/build/app/outputs/flutter-apk/app-ci-release.apk.qrcode.png

import os
import json
import socket
import string
import sys
import time
import getopt

import helperUtils as Utils

SCRIPT_DIR = os.path.dirname(__file__)
SCRIPT_NAME = os.path.basename(__file__)
_TAG = SCRIPT_NAME

Utils.log(_TAG, "======3======build argv:" + str(sys.argv))

try:
    import requests
except:
    Utils.log(_TAG, "import request exception! will install requests")
finally:
    Utils.log(_TAG, os.system("pip3 install requests"))
    Utils.log(_TAG, os.system("pip3 install requests-toolbelt"))
    pass

import requests

from requests_toolbelt import MultipartEncoder

NotifyType = ""
BuildDesc = ""
JenkinsBuildDescFile = ""
FilePath = ""
AndPath = ""

try:
    """
        options, args = getopt.getopt(args, shortopts, longopts=[])

        参数args：一般是sys.argv[1:]。过滤掉sys.argv[0]，它是执行脚本的名字，不算做命令行参数。
        参数shortopts：短格式分析串。例如："hp:i:"，h后面没有冒号，表示后面不带参数；p和i后面带有冒号，表示后面带参数。
        参数longopts：长格式分析串列表。例如：["help", "ip=", "port="]，help后面没有等号，表示后面不带参数；ip和port后面带冒号，表示后面带参数。

        返回值options是以元组为元素的列表，每个元组的形式为：(选项串, 附加参数)，如：('-i', '192.168.0.1')
        返回值args是个列表，其中的元素是那些不含'-'或'--'的参数。
    """
    opts, args = getopt.getopt(sys.argv[1:], "hu:p:",
                               ["help", "NotifyType=", "FilePath=", "AndPath="
                                   , "BuildDesc=", "JenkinsBuildDescFile="])
except getopt.GetoptError:
    sys.exit(2)
# 处理 返回值options是以元组为元素的列表。
for opt, arg in opts:
    if opt in ("-h", "--help"):
        sys.exit()
    elif opt in ("--NotifyType"):
        NotifyType = arg
    elif opt in ("--FilePath"):
        FilePath = arg
    elif opt in ("--AndPath"):
        AndPath = arg
    elif opt in ("--BuildDesc"):
        BuildDesc = arg
    elif opt in ("--JenkinsBuildDescFile"):
        JenkinsBuildDescFile = arg

Utils.log(_TAG, "NotifyType:" + NotifyType + " FilePath:" + FilePath)

fsAppid = "cli_a2284ef4eff8d013"
fsSecret = "CCiDH7WyU96ONQPUh0XL0crMzLqLrfeS"
fsWebHookUrl = ""
if NotifyType == "pub":
    fsWebHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/55d0a108-955e-4ca8-9b53-e2f846f15271"
elif NotifyType == "test":
    fsWebHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/13680e06-90b2-415d-a2c3-95619c4b7c32"



def fsMsg(imgKeys):
    Utils.log(_TAG, "feishu send msg")

    fsQrCodeItems = []

    for item in imgKeys.items():
        if item[0] == "ImgKey":
            fsQrCodeItems += [
                {
                    "tag": "img",
                    "title": {
                        "tag": "plain_text",
                        "content": "UnknownQrcode(?)👇"
                    },
                    "img_key": item["imgKey"],
                    "compact_width": True,
                    "alt": {
                        "tag": "plain_text",
                        "content": "qrcode"
                    }
                }
            ]
            pass

        if item[0] == "ApkQrcodeImgKey":
            build_info_json = SCRIPT_DIR+"/../android/buildInfo.json"
            version_info = ""
            if os.path.exists(build_info_json):
                version_info = open(build_info_json,"rt").read()
                version_info = "\n%s" % version_info
                pass
            fsQrCodeItems += [
                {
                    "tag": "img",
                    "title": {
                        "tag": "plain_text",
                        "content": "ApkQrcode(Android)👇%s" % version_info
                    },
                    "img_key": item[1],
                    "compact_width": True,
                    "alt": {
                        "tag": "plain_text",
                        "content": "qrcode"
                    }
                }
            ]
            pass

    final_build_desc = BuildDesc
    if os.path.exists(BuildDesc):
        final_build_desc = open(BuildDesc, 'rt').read()
        pass

    fsbody = {
        "msg_type": "interactive",
        "card": {
            "header": {
                "title": {
                    "tag": "plain_text",
                    "content": "Guang-Build-Notice（Error）"
                },
                "template": "red"
            },
            "config": {
                "wide_screen_mode": False
            },
            "elements": [
                {
                    "tag": "markdown",
                    "content": "<at id=all></at>"
                },
                {
                    "tag": "markdown",
                    "content": "**Build desc (developer):**\n{}\n --------------\n".format(final_build_desc)
                },
                {
                    "tag": "markdown",
                    "content": "**Build desc (environment):**\n{}\n --------------\n".format(open(JenkinsBuildDescFile, 'rt').read())
                },
            ]
        }
    }

    fsbody["card"]["elements"] += fsQrCodeItems

    res = requests.post(url=fsWebHookUrl, data=json.dumps(fsbody), headers={
        "Content-Type": "application/json"})
    Utils.log(_TAG, "Response:")
    Utils.log(_TAG, res.content)

    pass


def uploadFsImg(img_path: string):
    Utils.log(_TAG, "upload qrcode to feishu...")
    res = requests.post(url="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
                        data=json.dumps(
                            {"app_id": fsAppid, "app_secret": fsSecret}),
                        headers={"Content-Type": "application/json"})

    Utils.log(_TAG, "Response feishu img auth:")
    Utils.log(_TAG, res.content)
    if (res.status_code == 200):
        rJson = json.loads(res.content)
        tenant_access_token: string = rJson["tenant_access_token"]
    else:
        return None

    form = {'image_type': 'message',
            'image': (open(img_path, 'rb'))}
    multi_form = MultipartEncoder(form)
    headers = {'Authorization': "Bearer {}".format(tenant_access_token), 'Content-Type': multi_form.content_type}
    res = requests.post(
        url="https://open.feishu.cn/open-apis/im/v1/images", headers=headers, data=multi_form)
    Utils.log(_TAG, "Response upload fs img:")
    Utils.log(_TAG, res.content)
    rJson = json.loads(res.content)
    if rJson["code"] == 0:
        image_key: string = rJson["data"]["image_key"]
        Utils.log(_TAG, "upload qrcode to feishu suc: " + image_key)
        return image_key
    else:
        return None


def notify():
    aa = {}
    fsMsg(aa)
    pass


notify()
